<?php defined('SYSPATH') OR die('No direct access allowed.');

class Login_Controller extends Master_Home_Controller {
	
	public function ajax_signin() {
		if(request::is_ajax())
	    {
	    	$this->auto_render=false;
	    	$profiles = new Profiles_Model();
		    	
		    if($_POST) {
				$post = new Validation($_POST);
				$post->pre_filter('trim', TRUE);
            	$post->add_rules('txtUsername','required', 'length[3,50]');
            	$post->add_rules('txtPassword','required', 'length[3,20]');
				$post->post_filter('ucfirst', 'name');
	        	
	        	if (!$post->validate())
		        {
		        	// Not valid
		        	$errors = $post->errors('validate_error');
		        	
		        	$ajax = new ISS_Ajax();
		        	
		        	if (isset($errors['txtUsername'])) {
		        		$selector = "errUsername";
		        		$content = "<div id='errUsername' class='loginBlockError'>". $errors['txtUsername'] ."</div>";
						$ajax->addViewUpdate($selector, $content);
		        	}
		        	if (isset($errors['txtPassword'])) {
		        		$selector = "errPassword";
		        		$content = "<div id='errPassword' class='loginBlockError'>". $errors['txtPassword'] ."</div>";
						$ajax->addViewUpdate($selector, $content);
		        	}

		        	echo json_encode($ajax->getHtmlAjax()); //return a json encoded result
		        }
		        else {
		        	$ajax = new ISS_Ajax();
					$auth=new Auth;
					$user = ORM::factory('user',  $_POST['txtUsername']);
										
					if (!$user->loaded) {
						// User not found
						$post->add_error('txtUsername', 'user_not_found');
						$errors =  $post->errors('validate_error');
						
		        		$selector = "errUsername";
		        		$content = "<div id='errUsername' class='loginBlockError'>". $errors['txtUsername'] ."</div>";
						$ajax->addViewUpdate($selector, $content);
						
						$selector = "errPassword";
		        		$content = "<div id='errPassword' class='loginBlockError'></div>";
						$ajax->addViewUpdate($selector, $content);
						
						echo json_encode($ajax->getHtmlAjax());
					} 
					else if ($profiles->is_expired_user($user->id)) {
						$profiles->user_expired($user->id);
						$selector = "errUsername";
		        		$content = "<div id='errUsername' class='loginBlockError'>ชื่อผู้ใช้หมดอายุ</div>";
						$ajax->addViewUpdate($selector, $content);
						
						$selector = "errPassword";
		        		$content = "<div id='errPassword' class='loginBlockError'></div>";
						$ajax->addViewUpdate($selector, $content);
						
						echo json_encode($ajax->getHtmlAjax());
					} else if ($auth->login($user, $post['txtPassword'])) {
						// Sign in success
						$login_view = new View('login/logged');
						$this->user = $auth->get_user();
						
						
						$profile = $profiles->load($this->user->id)->current();
						
						$login_view->username = $profile['firstname'] . ' ' . $profile['lastname'];
						$login_view->picture = $profile['picture'];
						
						$ajax = new ISS_Ajax();
						$selector = "loginContainer";
		        		$content = $login_view;
		        		
		        		$ajax->addViewUpdate($selector, $content);
						echo json_encode($ajax->getHtmlAjax());
					} 
					else {
						// Worng password
						$post->add_error('txtPassword', 'invalid_password');
						$errors =  $post->errors('validate_error');
						
						$selector = "errUsername";
		        		$content = "<div id='errUsername' class='loginBlockError'></div>";
						$ajax->addViewUpdate($selector, $content);
						
		        		$selector = "errPassword";
		        		$content = "<div id='errPassword' class='loginBlockError'>". $errors['txtPassword'] ."</div>";
						$ajax->addViewUpdate($selector, $content);
						
						echo json_encode($ajax->getHtmlAjax());
					}
		        }
			}
	    }
	}
	
	public function signin() {
		if($_POST) {
			$post = new Validation($_POST);
			$post->pre_filter('trim', TRUE);
            $post->add_rules('txtUsername','required', 'length[3,50]');
            $post->add_rules('txtPassword','required', 'length[3,20]');
        	$post->post_filter('ucfirst', 'name');
        	
        	if (!$post->validate())
	        {
	        	$errors = $post->errors('validate_error');
	        	$view = new View('general/content');
		
				$login_view = new View('login/form');
				$login_view->errors = $errors;
				$view->login = $login_view;
				$this->set_title('Home');
				$this->template->content = $view;
				$this->template->render(TRUE);
	        }
	        else {
				$auth=new Auth;
				$user = ORM::factory('user',  $_POST['txtUsername']);
				if (!$user->loaded) {
					$post->add_error('login', 'user_not_found');
		        	$view = new View('general/content');
			
					$login_view = new View('login/form');
					$login_view->errors = $post->errors('validate_error');

					$view->login = $login_view;
					$this->set_title('Home');
					$this->template->content = $view;
					$this->template->render(TRUE);											
				} 
				else if ($auth->login($_POST['txtUsername'], $_POST['txtPassword'], false)) {
					url::redirect('index');
				} 
				else {
					$post->add_error('login', 'invalid_password');
		        	$view = new View('general/content');
			
					$login_view = new View('login/form');
					$login_view->errors = $post->errors('validate_error');
					
					$view->login = $login_view;
					$this->set_title('Home');
					$this->template->content = $view;
					$this->template->render(TRUE);
				}
				
	        }
		}
	}
	
	public function signout() {
		if($_POST) {
			$auth=new Auth;
			if ($auth->logged_in()) {
				$auth->logout();
				url::redirect('index');
			}
		}
	}
	
	public function request_forget_password() {
		$view = new View("member/forget_password");
        $view->title = "ลืมรหัสผ่าน";

        $master = new Masters_Model();
		// Get question master data
		$view->master_questions = $master->browse(3);
        
        $form = array (
					'txtForgetUsername'    => '',
					'cboForgetQuestion'   => '',
					'txtForgetAnswer' => '',
				);
        $view->form = $form;
        $view->render(TRUE);		
	}
	
	public function ajax_forget_password() {
		if(request::is_ajax())
	    {
	    	
	    	$this->auto_render=false;
		    	
		    if($_POST) {
				$post = new Validation($_POST);
				$post->pre_filter('trim', TRUE);
            	$post->add_rules('txtForgetUsername','required', 'length[3,50]');
            	$post->add_rules('cboForgetQuestion','required');
            	$post->add_rules('txtForgetAnswer','required', 'length[2,100]');
            	
				$post->post_filter('ucfirst', 'name');
	        	
	        	if (!$post->validate())
		        {
		        	// Not valid
		        	$errors = $post->errors('validate_error');
		        	
		        	$ajax = new ISS_Ajax();
		        	
		        	if (isset($errors['txtForgetUsername'])) {
		        		$selector = "errForgetUsername";
		        		$content = "<div id='errForgetUsername' class='loginBlockError'>". $errors['txtForgetUsername'] ."</div>";
						$ajax->addViewUpdate($selector, $content);
		        	}
		        	if (isset($errors['cboForgetQuestion'])) {
		        		$selector = "errForgetQuestion";
		        		$content = "<div id='errForgetQuestion' class='loginBlockError'>". $errors['cboForgetQuestion'] ."</div>";
						$ajax->addViewUpdate($selector, $content);
		        	}
		        	if (isset($errors['txtForgetAnswer'])) {
		        		$selector = "errForgetAnswer";
		        		$content = "<div id='errForgetAnswer' class='loginBlockError'>". $errors['txtForgetAnswer'] ."</div>";
						$ajax->addViewUpdate($selector, $content);
		        	}
		        	$selector = "forget_password_message";
	        		$content = '<div id="forget_password_message" class="loginBlockError">ระบบจะส่งข้อมูลรหัสผ่านไปให้ทางอีเมลล์ที่ได้ลงทะเบียนไว้</div>';
					$ajax->addViewUpdate($selector, $content);
		        	echo json_encode($ajax->getHtmlAjax()); //return a json encoded result
		        }
		        else {
		        	$ajax = new ISS_Ajax();
		        	$profiles = new Profiles_Model();
					$auth=new Auth;
					$user = ORM::factory('user',  $_POST['txtForgetUsername']);
					
					if (!$user->loaded) {
			        	$selector = "forget_password_message";
		        		$content = '<div id="forget_password_message" class="loginBlockError">ไม่พบข้อมูลผุ้ใช้งานตามที่ระบุ กรุณาตรวจสอบและลองใหม่</div>';
						$ajax->addViewUpdate($selector, $content);
						echo json_encode($ajax->getHtmlAjax());
					} 
					else if (!$profiles->is_valid_user($user->id, $_POST['cboForgetQuestion'], $_POST['txtForgetAnswer'])) {
						$selector = "forget_password_message";
		        		$content = '<div id="forget_password_message" class="loginBlockError">ข้อมูลที่ระบุไม่ถูกต้อง กรุณาตรวจสอบและลองใหม่</div>';
						$ajax->addViewUpdate($selector, $content);
						echo json_encode($ajax->getHtmlAjax());
					} 
					else if (!$profiles->get_new_password($user->id)) {
						$selector = "forget_password_message";
		        		$content = '<div id="forget_password_message" class="loginBlockError">พบข้อผิดพลาด กรุณาตรวจสอบและลองใหม่</div>';
						$ajax->addViewUpdate($selector, $content);
						echo json_encode($ajax->getHtmlAjax());
					} 
					else {
						$selector = "forget_password_message";
		        		$content = '<div id="forget_password_message" class="loginBlockError">ข้อมูลรหัสถูกส่งไปยัง email : '. $user->email .' เรียบร้อยแล้ว</div>';
						$ajax->addViewUpdate($selector, $content);
						echo json_encode($ajax->getHtmlAjax());
					}
		        }
			}	    	

	    }
	}
	
	public function request_change_password() {
		$view = new View("member/change_password");
        $view->title = "เปลี่ยนรหัสผ่าน";

        $form = array (
					'txtOldPassword'    => '',
					'txtNewPassword'   => '',
					'txtVerifyPassword' => '',
				);
        $view->form = $form;
        $view->render(TRUE);		
	}
	
	public function ajax_change_password() {
		if(request::is_ajax())
	    {
	    	
	    	$this->auto_render=false;
		    	
		    if($_POST) {
				$post = new Validation($_POST);
				$post->pre_filter('trim', TRUE);
            	$post->add_rules('txtOldPassword','required', 'length[3,50]');
            	$post->add_rules('txtNewPassword','required', 'length[3,50]');
            	$post->add_rules('txtVerifyPassword','required', 'length[3,50]');
            	
				$post->post_filter('ucfirst', 'name');
	        	
	        	if (!$post->validate())
		        {
		        	// Not valid
		        	$errors = $post->errors('validate_error');
		        	
		        	$ajax = new ISS_Ajax();
		        	
		        	if (isset($errors['txtOldPassword'])) {
		        		$selector = "errOldPassword";
		        		$content = "<div id='errOldPassword' class='loginBlockError'>". $errors['txtOldPassword'] ."</div>";
						$ajax->addViewUpdate($selector, $content);
		        	} 
		        	else {
		        		$selector = "errOldPassword";
		        		$content = "<div id='errOldPassword' class='loginBlockError'></div>";
						$ajax->addViewUpdate($selector, $content);
		        	}
		        	if (isset($errors['txtNewPassword'])) {
		        		$selector = "errNewPassword";
		        		$content = "<div id='errNewPassword' class='loginBlockError'>". $errors['txtNewPassword'] ."</div>";
						$ajax->addViewUpdate($selector, $content);
		        	}
		        	else {
		        		$selector = "errNewPassword";
		        		$content = "<div id='errNewPassword' class='loginBlockError'></div>";
						$ajax->addViewUpdate($selector, $content);
		        	}
		        	if (isset($errors['txtVerifyPassword'])) {
		        		$selector = "errVerifyPassword";
		        		$content = "<div id='errVerifyPassword' class='loginBlockError'>". $errors['txtVerifyPassword'] ."</div>";
						$ajax->addViewUpdate($selector, $content);
		        	}
		        	else {
		        		$selector = "errVerifyPassword";
		        		$content = "<div id='errVerifyPassword' class='loginBlockError'></div>";
						$ajax->addViewUpdate($selector, $content);
		        	}
		        	
		        	$selector = "change_password_message";
	        		$content = '<div id="change_password_message" class="loginBlockError">กดปุ่มยืนยันเพื่อเปลี่ยนรหัส</div>';
					$ajax->addViewUpdate($selector, $content);
		        	echo json_encode($ajax->getHtmlAjax()); //return a json encoded result
		        }
		        else {
		        	
		        	$ajax = new ISS_Ajax();
		        	$selector = "errOldPassword";
	        		$content = "<div id='errOldPassword' class='loginBlockError'></div>";
					$ajax->addViewUpdate($selector, $content);
		        	$selector = "errNewPassword";
	        		$content = "<div id='errNewPassword' class='loginBlockError'></div>";
					$ajax->addViewUpdate($selector, $content);
		        	$selector = "errVerifyPassword";
	        		$content = "<div id='errVerifyPassword' class='loginBlockError'></div>";
					$ajax->addViewUpdate($selector, $content);
						
		        	if ($_POST['txtNewPassword'] <> $_POST['txtVerifyPassword']) {
		        		
		        		$selector = "change_password_message";
	        			$content = '<div id="change_password_message" class="loginBlockError">กรุณาระบุรหัสผ่านใหม่ให้ตรงกัน และกดปุ่มยืนยันเพื่อเปลี่ยนรหัส</div>';
						$ajax->addViewUpdate($selector, $content);
						echo json_encode($ajax->getHtmlAjax());
		        	} else {
		        		
		        		$auth = new Auth();
		        		$user = $auth->get_user();
		        		$salt = $auth->find_salt($user->password);
		        		$password = $auth->hash_password($post['txtOldPassword'], $salt);
	
		        		if ($user->password <> $password) {
		        			$selector = "change_password_message";
		        			$content = '<div id="change_password_message" class="loginBlockError">ระบุรหัสผ่านปัจจุบันไม่ถูก กรุณาลองใหม่และกดปุ่มยืนยันเพื่อเปลี่ยนรหัส</div>';
							$ajax->addViewUpdate($selector, $content);
							echo json_encode($ajax->getHtmlAjax());
		        		}
		        		else {
			        		$profiles = new Profiles_Model();
			        		$data = array(
			        			'id' => $user->id,
			        			'password' => $_POST['txtNewPassword'],
			        		);
			        		if ($profiles->change_password($data)==TRUE) { 		        		
			        			$selector = "change_password_message";
			        			$content = '<div id="change_password_message" class="loginBlockError">เปลี่ยนแปลงรหัสผ่านเรียบร้อยแล้ว</div>';
								$ajax->addViewUpdate($selector, $content);
								echo json_encode($ajax->getHtmlAjax());
			        		} 
			        		else {
			        			$selector = "change_password_message";
			        			$content = '<div id="change_password_message" class="loginBlockError">ไม่สามารถเปลี่ยนแปลงรหัสผ่านได้ กรุณาลองใหม่อีกครั้ง</div>';
								$ajax->addViewUpdate($selector, $content);
								echo json_encode($ajax->getHtmlAjax());
			        		}
		        		}
		        	}
		        }
			}	    	
	    }
	}

	public function request_confirm_paid() {
		$view = new View("member/confirm_paid");

        $form = array (
					'txtConfirmPaidUsername'    => '',
					'txtConfirmPaidReferenceId'   => '',
					'txtConfirmPaidEvidentPicture' => '',
				);
        $view->form = $form;

        $this->set_title('สมาชิก - แจ้งชำระเงิน');
		$this->template->content = $view;
		$this->template->render(TRUE);
	}
	
	public function confirm_paid() {
		$profiles = new Profiles_Model();
	    Kohana::log('debug', 'confirm_paid');	
	    $view = new View("member/confirm_paid");
	    if($_POST) {
	    	Kohana::log('debug', 'confirm_paid post');
			$post = new Validation(array_merge($_POST, $_FILES));
			$post->pre_filter('trim', TRUE);
            $post->add_rules('txtConfirmPaidUsername','required', 'length[3,50]');
            $post->add_rules('txtConfirmPaidReferenceId','required', 'length[3,50]');
	        $post->add_rules('picture',
							'upload::valid', 
							'upload::type[gif,jpg,png]', 
							'upload::size[1M]'
	        );

	        $post->post_filter('ucfirst', 'name');
	        
			$form = array (
	        	'txtConfirmPaidUsername' => '',
				'txtConfirmPaidReferenceId' => '',
				'txtConfirmPaidEvidentPicture' => '',
	            );
			
	        if (!$post->validate())
	        {
	        	$errors = $post->errors('validate_error');
		
	        	$view->errors = $errors;
	        	$form['txtConfirmPaidUsername'] = (isset($_POST['txtConfirmPaidUsername']) ? $_POST['txtConfirmPaidUsername'] : '');
	        	$form['txtConfirmPaidReferenceId'] = (isset($_POST['txtConfirmPaidReferenceId']) ? $_POST['txtConfirmPaidReferenceId'] : '');
	        	$form['txtConfirmPaidEvidentPicture'] = (isset($_POST['txtConfirmPaidEvidentPicture']) ? $_POST['txtConfirmPaidEvidentPicture'] : '');
	        	$view->form = $form;
				$this->set_title('สมาชิก - แจ้งชำระเงิน');

				$this->template->content = $view;
				$this->template->render(TRUE);
	        }
	        else {
				Kohana::log('debug', 'confirm_paid::save');	        	
		       
	        	$profiles->file_evident_validate('txtConfirmPaidEvidentPicture');
	        	$filename = $profiles->get_evident_filename();
	        	Kohana::log('debug', 'confirm_paid::save file -> ' . $filename);

                $form['txtConfirmPaidUsername'] = (isset($_POST['txtConfirmPaidUsername']) ? $_POST['txtConfirmPaidUsername'] : '');
        		$form['txtConfirmPaidReferenceId'] = (isset($_POST['txtConfirmPaidReferenceId']) ? $_POST['txtConfirmPaidReferenceId'] : '');
	        	$form['txtConfirmPaidEvidentPicture'] = (isset($_POST['txtConfirmPaidEvidentPicture']) ? $_POST['txtConfirmPaidEvidentPicture'] : '');
	        	
	        	$auth=new Auth;
				$user = ORM::factory('user',  $_POST['txtConfirmPaidUsername']);
									
				if (!$user->loaded) {
					Kohana::log('debug', 'confirm_paid::user not found');
					$post->add_error('save_result', 'user_not_found');
				}
				else {
					$data = array(
		        		'id' => $user->id,
		        		'reference_id' => $_POST['txtConfirmPaidReferenceId'],
						'evident_picture' => str_replace(DOCROOT, '', $profiles->get_evident_filename()),
		        	);
		        	
					if ($profiles->confirm_paid($data)) {
						Kohana::log('debug', 'confirm_paid::save success');
		        		$post->add_error('save_result', 'save_completed');
		        	}
		        	else {
						Kohana::log('debug', 'confirm_paid::save fail');
		        		$post->add_error('save_result', 'save_failed');
		        	}
				}
				$view->errors = $post->errors('validate_error');;
				$view->form = $form;
				$this->set_title('สมาชิก - แจ้งชำระเงิน');

				$this->template->content = $view;
				$this->template->render(TRUE);
				
	        }
		}	    	
	}
	
}